package com.fang.fen.blog.user.mapper;

import com.fang.fen.blog.user.domain.User;
import com.github.pagehelper.Page;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.jdbc.SQL;


@Mapper
public interface UserMapper {

    String TABLE = "T_USER";

    @Insert("INSERT INTO T_USER " +
            "(id, account, email, password, name, mobile, birthday, sex) " +
            "SELECT " +
            "#{user.id}, #{user.account},#{user.email},#{user.password},#{user.name},#{user.mobile},#{user.birthday},#{user.sex} " +
            "FROM DUAL " +
            "WHERE NOT EXISTS (SELECT 1 FROM T_USER WHERE account = #{user.account}) ")
    int save(@Param("user") User user);

    @Select("select * from t_user where id = #{id}")
    User findOne(@Param("id") String id);


    @Select("select * from t_user where id = #{name}")
    User findByName(@Param("name") String name);

    @SelectProvider(type = SqlBuilder.class, method = "buildFindByPage")
    Page<User> findByPage(@Param("user") User user);


    class SqlBuilder {

        static String SELECT_USER =
                "id, account, name, email, mobile, disabled, sex, birthday, create_time as createTime, update_time as updateTime";

        static String LIKE_NAME = "name like CONCAT('%', #{user.name}, '%')";

        static String LIKE_ACCOUNT = "account like CONCAT('%', #{user.account}, '%')";

        static String LIKE_EMAIL = "email like CONCAT('%', #{user.email}, '%')";

        static String EQ_MOBILE = "mobile = #{user.mobile}";

        public String buildFindByPage(@Param("user") User user) {
            return new SQL() {{
                SELECT(SELECT_USER);
                FROM(TABLE);
                if (StringUtils.isNotEmpty(user.getName())) {
                    WHERE(LIKE_NAME);
                }
                if (StringUtils.isNotEmpty(user.getAccount())) {
                    WHERE(LIKE_ACCOUNT);
                }
                if (StringUtils.isNotEmpty(user.getEmail())) {
                    WHERE(LIKE_EMAIL);
                }
                if (StringUtils.isNotEmpty(user.getMobile())) {
                    WHERE(EQ_MOBILE);
                }
            }}.toString();
        }
    }

}
